package com.sk.weichat.ui.circle;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.ConstraintSet;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.cjt2325.cameralibrary.util.ScreenUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.githang.statusbar.StatusBarCompat;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.sk.weichat.R;
import com.sk.weichat.adapter.DynamicHeadAdapter;
import com.sk.weichat.bean.DynamicBean;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.MediaPlayerHelper;
import com.sk.weichat.util.ScreenUtil;
import com.sk.weichat.util.keyboard.KeyboardHeightObserver;
import com.sk.weichat.util.keyboard.KeyboardHeightProvider;

import java.io.IOException;
import java.text.DecimalFormat;

import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * @author lzs
 * @date 2019/10/23
 * Email:343067508@qq.com
 **/
public class DynamicVideoDetailsActivity2 extends BaseActivity implements KeyboardHeightObserver, TextureView.SurfaceTextureListener, MediaPlayerHelper.MediaPlayerListener, DynamicHeadAdapter.OnItemClickListener {
    private DelegateAdapter delegateAdapter;
    private SmartRefreshLayout refreshLayout;
    //监听键盘弹起收回状态
    KeyboardHeightProvider keyboardHeightProvider;
    //
    TextureView textureView;
    //
    View layoutCommentInput;

    TextView tvTime;
    //顶部昵称
    TextView tvName;
    //顶部头像
    SimpleDraweeView ivAvatarTop;
    //底部输入框头像
    SimpleDraweeView ivAvatar;
    TextView tvAttention;
    int actionBarHeight; //顶部标题栏高度
    ConstraintLayout controlView;
    DynamicBean dynamicBean;
    VirtualLayoutManager layoutManager;
    DynamicHeadAdapter adapter;

    public static void startDynamicVideoDetailsActivity(Activity activity, TextureView textureView, DynamicBean dynamicBean) {
        Intent intent = new Intent(activity, DynamicVideoDetailsActivity2.class);
        intent.putExtra(DynamicBean.DynamicBean_Key, (Parcelable) dynamicBean);
        ActivityOptionsCompat optionsCompat =
                ActivityOptionsCompat.makeSceneTransitionAnimation(activity, textureView, activity.getString(R.string.dynamic_video_transition_name));
        activity.startActivity(intent, optionsCompat.toBundle());
    }

    public static void startDynamicVideoDetailsActivity(Context context, DynamicBean dynamicBean) {
        Intent intent = new Intent(context, DynamicVideoDetailsActivity2.class);
        intent.putExtra(DynamicBean.DynamicBean_Key, (Parcelable) dynamicBean);
        context.startActivity(intent);
    }

    private final static int updateProgressMsg = 19;
    private final int updateProgress_alternation = 200;//毫秒更新一次进度条

    private Handler progressTimer = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (MediaPlayerHelper.getInstance().getPlayerState() == MediaPlayerHelper.state_playing) {
                long duration = MediaPlayerHelper.getInstance().getDuration();
                long current = MediaPlayerHelper.getInstance().getCurrentPosition();
                //Log.e("lzs", "duration:" + duration + "  current:" + current);
                updateProgressAndTime(duration, current);
            }
            startProgressUpdateTimer();
            return true;
        }
    });

    DecimalFormat decimalFormat = new DecimalFormat("00");

    private String formatVideoDuration(long duration) {
        int time = Math.round(duration * 1.0f / 1000);
        int second = time % 60;
        int minute = time / 60;
        int hour = time % 60 / 60;
        return (hour == 0 ? "" : decimalFormat.format(hour) + ":") + decimalFormat.format(minute) + ":" + decimalFormat.format(second);
    }

    private void updateProgressAndTime(long duration, long progress) {
        SeekBar seekBar = controlView.findViewById(R.id.seekbar);
        seekBar.setMax((int) duration);
        seekBar.setProgress((int) progress);
        TextView tvDuration = controlView.findViewById(R.id.tv_total_time);
        tvDuration.setText(formatVideoDuration(duration) + "''");

        TextView tvCurrentTime = controlView.findViewById(R.id.tv_current_position);
        tvCurrentTime.setText(formatVideoDuration(progress) + "''");
    }

    /**
     * 开始进度条更新计时器
     */
    private void startProgressUpdateTimer() {
        if (progressTimer != null) {
            progressTimer.removeMessages(updateProgressMsg);
            progressTimer.sendEmptyMessageDelayed(updateProgressMsg, updateProgress_alternation);
        }
    }

    /**
     * 停止进度条更新计时器
     */
    private void stopProgressUpdateTimer() {
        if (progressTimer != null) {
            progressTimer.removeMessages(updateProgressMsg);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_video_details2);
        StatusBarCompat.setLightStatusBar(getWindow(), false);
        ConstraintLayout actionBar = findViewById(R.id.actionBar);
        actionBar.setPadding(0, ScreenUtil.getStatusHeight(mContext), 0, 0);
        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) actionBar.getLayoutParams();
        lp.height += ScreenUtil.getStatusHeight(mContext);
        actionBar.setLayoutParams(lp);
        actionBar.findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        dynamicBean = getIntent() != null ? getIntent().getParcelableExtra(DynamicBean.DynamicBean_Key) : null;
        dynamicBean.setActive(false);
        textureView = findViewById(R.id.textureView);

        layoutTextureByRotation();


        //Log.e("lzs", "dynamicBean.getVideoHeight():" + dynamicBean.getVideoHeight() + "  getVideoWidth:" + dynamicBean.getVideoWidth());
        textureView.setSurfaceTextureListener(this);

        controlView = findViewById(R.id.control_view);

        setControlView();

        layoutCommentInput = findViewById(R.id.layout_input_comment);

        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        layoutManager = new VirtualLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);

        delegateAdapter = new DelegateAdapter(layoutManager, false);
        recyclerView.setAdapter(delegateAdapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int totalY = 0;

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (dx == 0 && dy == 0) {
                    return;
                }
                totalY += dy;
                if (totalY >= actionBarHeight) {
                    //显示顶部的头像和标题栏
                    TransitionManager.beginDelayedTransition(actionBar);
                    ConstraintSet constraintSet1 = new ConstraintSet();
                    constraintSet1.clone(mContext, R.layout.layout_dynamic_video_head_action_scroll);
                    constraintSet1.applyTo(actionBar);
                } else {
                    //
                    TransitionManager.beginDelayedTransition(actionBar);
                    ConstraintSet constraintSet1 = new ConstraintSet();
                    constraintSet1.clone(mContext, R.layout.layout_dynamic_video_head_action_nomal);
                    constraintSet1.applyTo(actionBar);
                }

            }
        });
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                actionBarHeight = actionBar.getHeight();
                keyboardHeightProvider = new KeyboardHeightProvider(DynamicVideoDetailsActivity2.this);
                keyboardHeightProvider.setKeyboardHeightObserver(DynamicVideoDetailsActivity2.this);
                keyboardHeightProvider.start();
            }
        });

        refreshLayout = findViewById(R.id.refresh_layout);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

            }
        });
        if (dynamicBean != null) {
            adapter = new DynamicHeadAdapter(dynamicBean, mContext);
            adapter.setListener(this);
            delegateAdapter.addAdapter(adapter);
            delegateAdapter.notifyDataSetChanged();
            recyclerView.post(new Runnable() {
                @Override
                public void run() {
                    View target = findTarget(layoutManager);
                    attachVideoViewTo(target);
                }
            });
        }
    }

    private void layoutTextureByRotation() {
        ConstraintLayout.LayoutParams lp2 = (ConstraintLayout.LayoutParams) textureView.getLayoutParams();
//        Log.e("lzs", "dynamicBean.getVideoHeight():" + dynamicBean.getVideoHeight() + "   dynamicBean.getVideoWidth():" + dynamicBean.getVideoWidth());
//        Log.e("lzs", "getRotation:" + dynamicBean.getRotation());
        if (dynamicBean.getRotation() / 90 > 0) {
            //旋转90
            //Log.e("lzs", "视频旋转了：" + dynamicBean.getRotation());
            lp2.width = DynamicHeadAdapter.getVideoSize(ScreenUtil.getScreenWidth(mContext), dynamicBean.getVideoHeight(), dynamicBean.getVideoWidth())[1];
            lp2.height = ScreenUtil.getScreenWidth(mContext);
            textureView.setLayoutParams(lp2);
            textureView.setRotation(dynamicBean.getRotation());
        } else {
            lp2.width = ScreenUtil.getScreenWidth(mContext);
            lp2.height = DynamicHeadAdapter.getVideoSize(ScreenUtil.getScreenWidth(mContext), dynamicBean.getVideoWidth(), dynamicBean.getVideoHeight())[1];
            textureView.setLayoutParams(lp2);
        }
        MediaPlayerHelper.getInstance().setVideoCenter(textureView, lp2.width, lp2.height, lp2.width, lp2.height);
        //Log.e("lzs", "lp2 w:" + lp2.width + "   lp2 h:" + lp2.height);
    }

    /**
     * textureview 依附在 active 的列表item上
     *
     * @param target
     */
    private boolean flag;

    private void attachVideoViewTo(View target) {
        if (textureView == null || !textureView.isAttachedToWindow()) {
            return;
        }
        if (!flag) {
            flag = true;
            target.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                int originalX;
                int originalY;

                @Override
                public void onGlobalLayout() {
                    int[] location = new int[2];
                    target.getLocationOnScreen(location);
                    if (originalX != location[0] || originalY != location[1]) {
                        // Log.e("lzs", "location[0]:" + location[0] + "  location[1]:" + location[1]);
                        originalX = location[0];
                        originalY = location[1];
                        int height = target.getHeight();
                        int width = target.getWidth();
                        Log.e("lzs", "target h:" + height + "  target w:" + width);
                        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) textureView.getLayoutParams();
                        lp.height = height;
                        lp.width = width;
                        if (dynamicBean.getRotation() / 90 > 0) {
                            lp.height = width;
                            lp.width = height;
                        }
//                        lp.topMargin = location[1];
                        //  Log.e("lzs", "lp.topMargin:" + lp.topMargin);
//                        lp.leftMargin = location[0];
                        textureView.setLayoutParams(lp);
                        textureView.setTranslationX(location[0]);
                        textureView.setTranslationY(location[1]);
                        controlView.setTranslationX(location[0]);
                        controlView.setTranslationY(location[1]);
                    }
                }
            });
        }
    }


    private View findTarget(RecyclerView.LayoutManager layoutManager) {
        View view = layoutManager.findViewByPosition(0);
        View ivCover = view.findViewById(R.id.view_touch);
        return ivCover;
    }

    private void setControlView() {
        controlView.findViewById(R.id.iv_pause).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageView ivPause = controlView.findViewById(R.id.iv_pause);
                //暂停按键
                if (MediaPlayerHelper.getInstance().getPlayerState() == MediaPlayerHelper.state_playing) {
                    ivPause.setImageResource(R.drawable.icon_chat_play);
                    MediaPlayerHelper.getInstance().pause();
                } else if (MediaPlayerHelper.getInstance().getPlayerState() == MediaPlayerHelper.state_pause) {
                    ivPause.setImageResource(R.drawable.icon_video_pause);
                    MediaPlayerHelper.getInstance().start();
                }
            }
        });
        SeekBar seekBar = controlView.findViewById(R.id.seekbar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {

                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //MediaPlayerHelper.getInstance().pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (dynamicBean.isActive()) {
                    MediaPlayerHelper.getInstance().seekTo(seekBar.getProgress());
                } else {
                    seekBar.setProgress(0);
                }
            }
        });
        controlView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Object tag = controlView.getTag();
                if (tag == null) {
                    showOrHideControlView(true);
                    controlView.setTag(true);
                }
                if (tag != null) {
                    boolean flag = (boolean) tag;
                    if (flag) {
                        showOrHideControlView(false);
                        controlView.setTag(false);
                    } else {
                        showOrHideControlView(true);
                        controlView.setTag(true);
                    }
                }
            }
        });
    }


    private void showOrHideControlView(boolean show) {
        if (show) {
            //点击展示进度条和时间
            TransitionManager.beginDelayedTransition(controlView);
            ConstraintSet constraintSet1 = new ConstraintSet();
            constraintSet1.clone(mContext, R.layout.layout_dynamic_video_control_view);
            constraintSet1.applyTo(controlView);
        } else {
            //点击展示进度条和时间
            TransitionManager.beginDelayedTransition(controlView);
            ConstraintSet constraintSet1 = new ConstraintSet();
            constraintSet1.clone(mContext, R.layout.layout_dynamic_video_control_view_hide);
            constraintSet1.applyTo(controlView);
        }
    }

    @Override
    public void onKeyboardHeightChanged(int height, int orientation) {
        if (height > 0) {
            //弹起
            ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) layoutCommentInput.getLayoutParams();
            lp.bottomMargin = height;
            layoutCommentInput.setLayoutParams(lp);
        } else {
            //收回
            ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) layoutCommentInput.getLayoutParams();
            lp.bottomMargin = 0;
            layoutCommentInput.setLayoutParams(lp);
        }
    }

    @Override
    protected void onResume() {
        if (dynamicBean.isActive()) {
            MediaPlayerHelper.getInstance().start();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //if (dynamicBean.isActive()) {
        MediaPlayerHelper.getInstance().pause();
        //}
    }

    @Override
    protected void onDestroy() {
        keyboardHeightProvider.close();
        progressTimer.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        if (dynamicBean.getBody().getVideos() == null || dynamicBean.getBody().getVideos().size() == 0) {
            return;
        }
        //Log.e("lzs", "onSurfaceTextureAvailable width:" + width + "  height:" + height);
        String currentUrl = MediaPlayerHelper.getInstance().getCurrentUrl();
        String url = dynamicBean.getBody().getVideos().get(0).getOriginalUrl();
        //判断两个url是否一致
        if (!TextUtils.isEmpty(currentUrl) && currentUrl.equalsIgnoreCase(url)) {
            dynamicBean.setActive(true);
            //一致则直接切换播放界面，继续播放
            MediaPlayerHelper.getInstance().changeSurface(surface);
            MediaPlayerHelper.getInstance().start();
        } else {
            //不一致则重新设置视频源
            try {
                MediaPlayerHelper.getInstance().setMediaPlayerHelperListener(this);
                MediaPlayerHelper.getInstance().prepare(surface, dynamicBean.getBody().getVideos().get(0).getOriginalUrl(), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        dynamicBean.setActive(true);
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        startProgressUpdateTimer();
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }

    @Override
    public boolean onInfo(IMediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onVideoSizeChanged(IMediaPlayer mp, int width, int height) {

    }

    @Override
    public void onSeekComplete(IMediaPlayer mp) {
        Log.e("lzs", "onSeekComplete");
    }

    @Override
    public void onBufferingUpdate(IMediaPlayer mp, int percent) {
        Log.e("lzs", "onBufferingUpdate:" + percent);
    }

    @Override
    public boolean onError(IMediaPlayer mp, int what, int extra) {
        Log.e("lzs", "onError  what:" + what + " extra: " + extra);
        return false;
    }

    @Override
    public void onCompletion(IMediaPlayer mp) {

    }

    @Override
    public void onPrepared(IMediaPlayer mp) {

    }

    @Override
    public void onItemClick(View view, int position) {

    }
}
